<template>
  <t-drawer
    v-model:visible="formVisible"
    size="medium"
    size-draggable
    :footer="false"
    :header="isEdit ? '编辑' : '新增'"
  >
    <div>
      <t-form ref="formRef" :data="form" :rules="rules" @submit="onSubmit">
        <t-form-item name="type" label="类型">
          <t-input v-model="form.type" placeholder="请填写用户名" />
        </t-form-item>
        <t-form-item name="description" label="描述">
          <t-input v-model="form.description" placeholder="请填写描述" />
        </t-form-item>
        <t-form-item>
          <t-button variant="outline" @click="close">取消</t-button>
          <t-button theme="primary" type="submit">确定</t-button>
        </t-form-item>
      </t-form>
    </div>
  </t-drawer>
</template>

<script lang="ts" setup>
import { MessagePlugin, SubmitContext } from 'tdesign-vue-next';
import { computed, ref } from 'vue';

import { addDict, updateDict } from '@/api/upms/dict';
import { useVisible } from '@/hooks/visible';

const formRef = ref();

const initData = () => {
  return {
    id: '',
    type: '',
    description: '',
  };
};

const rules = {
  type: [
    {
      required: true,
      message: '类型不能为空',
    },
  ],
  description: [
    {
      required: true,
      message: '描述不能为空',
    },
  ],
};

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  formData: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const emit = defineEmits<{
  (e: 'update:visible', v: boolean): void;
  (e: 'refresh'): void;
}>();

const form = ref(props.formData);

const { formVisible, close, open } = useVisible(props, emit);

// 判断是编辑还是新增
const isEdit = computed(() => !!form.value.id);

const onSubmit = async ({ validateResult, firstError }: SubmitContext<FormData>) => {
  if (validateResult === true) {
    if (isEdit.value) {
      await updateDict(form.value).then(() => {
        MessagePlugin.success('修改成功');
      });
    } else {
      await addDict(form.value).then(() => {
        MessagePlugin.success('添加成功');
      });
    }
    form.value = { ...initData };
    formVisible.value = false;
    emit('refresh');
  } else {
    MessagePlugin.warning(firstError);
  }
};

open(() => {
  const { id } = props.formData;
  if (id) {
    form.value = props.formData;
  } else {
    form.value = initData();
  }
});
</script>
